package com.ygxsk.carhome.ui.paintbook;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.KeyboardUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.NetworkUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.flyco.roundview.RoundTextView;
import com.gyf.immersionbar.ImmersionBar;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.core.BasePopupView;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;
import com.trello.rxlifecycle4.android.ActivityEvent;
import com.ygxsk.carhome.R;
import com.ygxsk.carhome.constant.ConstantApi;
import com.ygxsk.carhome.constant.ConstantSign;
import com.ygxsk.carhome.constant.ExtraKey;
import com.ygxsk.carhome.constant.ExtraValue;
import com.ygxsk.carhome.event.EventPaintBookingMain;
import com.ygxsk.carhome.listener.ErrorParentExtraSingle;
import com.ygxsk.carhome.listener.RxBus;
import com.ygxsk.carhome.response.BookingInsideBean;
import com.ygxsk.carhome.response.BookingOutsideBean;
import com.ygxsk.carhome.response.PaintBookingPayFee;
import com.ygxsk.carhome.retrofit.AddLogUpLoadInfo;
import com.ygxsk.carhome.retrofit.ApiException;
import com.ygxsk.carhome.retrofit.ApiRequestSubListener;
import com.ygxsk.carhome.retrofit.ApiService;
import com.ygxsk.carhome.retrofit.ErrorConsumer;
import com.ygxsk.carhome.retrofit.NetworkManager;
import com.ygxsk.carhome.retrofit.ResponseTransformer;
import com.ygxsk.carhome.rxbus.RxBusCalendarTimeForAgreement;
import com.ygxsk.carhome.ui.ErrorActivity;
import com.ygxsk.carhome.ui.adapter.BookingOutsideAdapter;
import com.ygxsk.carhome.ui.evaluate.CalendarViewCustomPopup;
import com.ygxsk.carhome.utils.CommUtils;
import com.ygxsk.carhome.utils.DateUtilFir;
import com.ygxsk.carhome.utils.TimeUtilSer;
import com.ygxsk.carhome.views.MyLinearLayoutManager;
import com.ygxsk.integrated.retrofit.Parameterkey;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.functions.Consumer;
import okhttp3.MediaType;
import okhttp3.RequestBody;

/*
 * @Author:itchenqi175@163.com
 * @Time:2023-09-09  16:33
 * @Description:添加 钣金喷漆的预约时间
 */
public class PaintBookingMainActivity extends ErrorActivity implements ErrorParentExtraSingle {

//    private ActivityPaintBookingMainBinding activityPaintBookingMainBinding;

    @BindView(R.id.refreshLayoutInBooking)
    SmartRefreshLayout refreshLayoutInBooking;

    @BindView(R.id.recyclerViewInBooking)
    RecyclerView recyclerViewInBooking;

    @BindView(R.id.roundbuttontopayment)
    RoundTextView roundButtonToPayMent;

    //添加内容
    private ArrayList<BookingOutsideBean> mDataResources = new ArrayList<>();
    //添加外侧的布局适配器
    private BookingOutsideAdapter bookingOutsideAdapter;

    //弹窗关于签约时间的
    private BasePopupView basePopupViewAgreenmentTime;

    //目前当前的日期，用来和后边选中时间做比对
    private String appointDate_current = "";
    //上传用时间 日期
    private String appointDate_upLoad = "";

    //微信支付包裹内容====================================================
    //添加做接口提交的时间 上传
//    private String useTime_upLoad;
    //做上传 选中的房间号和该房间预约时间段-这里的outSide标识的 是外侧的喷涂房间
    private ArrayList<PaintBookIngSiteOutSideUpLoad> siteList_upLoad = new ArrayList<>();

    //微信支付包裹内容====================================================
//    private IWXAPI mWinXinApi;

    /**
     * 立即付款支付列表面板内容
     */
//    private BaseBottomDialog payDialogPanel;
    /**
     * 用于加密之后密码上传内容
     */
//    private String passwordStringPass = "";
    /**
     * 获取默认的支付方式
     */
//    private String payTypeCode;

    /**
     * 支付面板传回来的支付方式实体
     */
//    private PayTypeList curCheckPayTypeBean = null;

    /**
     * 临时存放支付方式列表信息
     */
//    private ArrayList<PayTypeList> payTypeLists = new ArrayList<>();

    /**
     * 预付单号。可以单独拿出来
     */
//    private String beforeReceiptNo;

    //微信支付包裹内容====================================================
    @OnClick({R.id.roundbuttontopayment})//
    public void onViewClickInPaintBookingMain(View viewInside) {

        switch (viewInside.getId()) {

            case R.id.roundbuttontopayment: {//提交预约

                //弹窗支付弹窗的列表：
//                if (!DoubleClickListener.isFastDoubleClick()) {
//                    showPayDialog();
//                }
                //跳转到结算页，获取接口 看看是否能正常支付的
//                Bundle extra_bundle = new Bundle();
//                ActivityUtils.startActivity(extra_bundle, PaintBookingFeeActivity.class);

                //校验是否是没有选中就提交；
//                //过滤适配器，
//                Observable.fromIterable(mDataResources)
//                        .compose(PaintBookingMainActivity.this.bindUntilEvent(ActivityEvent.DESTROY))//
//                        .doOnSubscribe(new Consumer<Disposable>() {
//                            @Override
//                            public void accept(Disposable disposable) throws Exception {
//
//                                LogUtils.d("itchen--选中的房间--doOnSubscribe---在执行订阅之前先 ---清空处理--->" + disposable.isDisposed());
//
//                                if (!siteList_upLoad.isEmpty()) {
//                                    siteList_upLoad.clear();
//                                }
//
//                            }
//                        }).subscribeOn(AndroidSchedulers.mainThread())//
//                        .observeOn(AndroidSchedulers.mainThread())//
//                        .filter(new Predicate<BookingOutsideBean>() {
//                            @Override
//                            public boolean test(BookingOutsideBean bookingOutsideBean) throws Exception {
//
//                                LogUtils.d("itchen--filter---test--选择房间-测试了--->" + bookingOutsideBean.getSiteNo() + "--id==>" + bookingOutsideBean.getSpraySiteId());
//                                return bookingOutsideBean.isChecked();
//                            }
//                        }).subscribe(new Consumer<CategoryAddBottomBean>() {
//                            @Override
//                            public void accept(CategoryAddBottomBean categoryAddBottomBean) throws Exception {
//
////                                LogUtils.d("itchen--subscribe--物品所属空间--accept--最终符合条件的--->" + //
////                                categoryAddBottomBean.getSpaceKind() + "id==>" + categoryAddBottomBean.getSpaceId()//
////                                + "-categoryAddBottomBean=>" + categoryAddBottomBean.toString());//
//                                tagSpaceIdsPass.add(categoryAddBottomBean.getSpaceId());
//
//                            }
//                        });

                //执行之前先清空已经存在的，再次过滤一次
                if (siteList_upLoad != null && !siteList_upLoad.isEmpty()) {
                    siteList_upLoad.clear();
                }

                //校验时间的是否选中
                if (TextUtils.isEmpty(appointDate_upLoad)) {
                    CommUtils.checkDialog(mAlertView);
                    mAlertView = CommUtils.method_showAlertViewSingleSlowly(mActivityInstance, ConstantSign.ALERT_TITLE, getString(R.string.please_choose_time_date), true);
                    mAlertView.show();
                    return;
                }

                //外侧的 喷涂房间号的添加
                //创建一个接收传递的对象
                //遍历外侧房间 的内部的 时间段的选中
//                if (mDataResources != null && !mDataResources.isEmpty()) {
//
//                    Iterator<BookingOutsideBean> iteratorOutSide = mDataResources.iterator();
//
//                    if (iteratorOutSide != null) {
//
//                        while (iteratorOutSide.hasNext()) {
//
//                            BookingOutsideBean itemOutSide = iteratorOutSide.next();
//
//                            if (itemOutSide != null) {
//
//                                //创建喷涂房间的预约上传接收；
//                                PaintBookIngSiteOutSideUpLoad paintBookIngSiteOutSideUpLoad = new PaintBookIngSiteOutSideUpLoad();
//                                paintBookIngSiteOutSideUpLoad.setSpraySiteId(itemOutSide.getSpraySiteId());
//
//                                if ((itemOutSide.getSiteTimeSpans() != null) && (!itemOutSide.getSiteTimeSpans().isEmpty())) {
//
//                                    //----------------------------------------------------------------------------------------------
//                                    //内部的时间段的循环
//                                    Iterator<BookingInsideBean> iteratorInSide = itemOutSide.getSiteTimeSpans().iterator();
//
//                                    if (iteratorInSide != null) {
//
//                                        while (iteratorInSide.hasNext()) {
//
//                                            BookingInsideBean itemInSide = iteratorInSide.next();
//
//                                            if (itemInSide != null) {
//
//                                                if (itemInSide.isChecked()) {//判断条件
//
//                                                    //创建一个 此房间的 时间段的接收器，并且给该时间段设置到外侧的房间号；
//                                                    PaintBookIngSiteInSideUpLoad paintBookIngSiteInSideUpLoad = new PaintBookIngSiteInSideUpLoad();
//                                                    paintBookIngSiteInSideUpLoad.setSiteTimeSpanId(itemInSide.getSiteTimeSpanId());
//
//                                                    paintBookIngSiteOutSideUpLoad.getSiteTimeSpans().add(paintBookIngSiteInSideUpLoad);
//
//                                                    //这条有效数据要加到 上传对象之中;
//                                                    if (siteList_upLoad != null) {
//                                                        siteList_upLoad.add(paintBookIngSiteOutSideUpLoad);
//                                                    }
//
////                                                    LogUtils.json(ConstantSign.LOGCAT_NOMAL + "这条 预约喷涂房间段 的有效数据是--itemOutSide", itemOutSide);
//                                                    LogUtils.d(ConstantSign.LOGCAT_NOMAL + "这条 预约喷涂房间段 的有效数据是--itemOutSide--所属房间号是-->" + itemOutSide.getSiteNo() + "房间号id-->" + itemOutSide.getSpraySiteId());
//                                                    LogUtils.json(ConstantSign.LOGCAT_NOMAL + "这条 预约时间段 的有效数据是-----itemInSide--", itemInSide);
//
//                                                } else {
////                                                    LogUtils.d(ConstantSign.LOGCAT_NOMAL + "这是 喷涂预约时间的 无效数据 ");
//                                                }
//
//                                            }
//
//                                        }
//                                    }
//
//                                    //----------------------------------------------------------------------------------------------
//
//                                }
//                            }
//                        }
//                    }
//                }


                //for遍历
                if (mDataResources != null && !mDataResources.isEmpty()) {

                    for (BookingOutsideBean itemOutSide : mDataResources) {

                        if (itemOutSide != null) {

                            //传递的对象外层包裹；
                            PaintBookIngSiteOutSideUpLoad paintBookIngSiteOutSideUpLoad = new PaintBookIngSiteOutSideUpLoad();
                            paintBookIngSiteOutSideUpLoad.setSpraySiteId(itemOutSide.getSpraySiteId());


                            for (BookingInsideBean itemInSide : itemOutSide.getSiteTimeSpans()) {

                                if (itemInSide != null) {

                                    if (itemInSide.isChecked()) {

                                        //创建一个 此房间的 时间段的接收器，并且给该时间段设置到外侧的房间号；
                                        PaintBookIngSiteInSideUpLoad paintBookIngSiteInSideUpLoad = new PaintBookIngSiteInSideUpLoad();
                                        paintBookIngSiteInSideUpLoad.setSiteTimeSpanId(itemInSide.getSiteTimeSpanId());

                                        if (paintBookIngSiteOutSideUpLoad.getSiteTimeSpans() != null) {
                                            paintBookIngSiteOutSideUpLoad.getSiteTimeSpans().add(paintBookIngSiteInSideUpLoad);
                                        }

//                                      LogUtils.json(ConstantSign.LOGCAT_NOMAL + "这条 预约喷涂房间段 的有效数据是--itemOutSide", itemOutSide);
                                        LogUtils.json(ConstantSign.LOGCAT_NOMAL + "这条 预约时间段 的有效数据是-----itemInSide--", itemInSide);


                                    }

                                }

                            }

                            //------------------------------------------------------------------------------------------

                            //这条有效数据要加到 上传对象之中;
                            if (siteList_upLoad != null) {
                                //如果有选中的再添加
                                if ((paintBookIngSiteOutSideUpLoad.getSiteTimeSpans() != null) && (!paintBookIngSiteOutSideUpLoad.getSiteTimeSpans().isEmpty())) {
                                    siteList_upLoad.add(paintBookIngSiteOutSideUpLoad);
                                }
                            }

//                            LogUtils.d(ConstantSign.LOGCAT_NOMAL + "这条 预约喷涂房间段 的有效数据是--itemOutSide--所属房间号是-->" + itemOutSide.getSiteNo() + "房间号id-->" + itemOutSide.getSpraySiteId());

                        }
                    }

                }

                //判断 siteList_upLoad 的值是否为空，如果长度为空 不能到结算页；
                if (siteList_upLoad != null && siteList_upLoad.isEmpty()) {
                    CommUtils.checkDialog(mAlertView);
                    mAlertView = CommUtils.method_showAlertViewSingleSlowly(mActivityInstance, ConstantSign.ALERT_TITLE, getString(R.string.please_input_sitetimespanid), true);
                    mAlertView.show();
                    return;
                }

                //添加真实的填充数据
//                {
//                        "useTime": "2023-10-12", //预约日期
//                        "siteList": [
//                             {
//                            "spraySiteId": 4, //房间ID
//                            "siteTimeSpans": [
//                                {
//                                "siteTimeSpanId": 31 //时段ID
//                               }
//                              ] //预约时段集合
//                         }
//                   ] //房间集合
//                }

                //传递的是一个json
                HashMap<String, Object> map = new HashMap<>();
//              map.put(Parameterkey.shopInfoId, mSession.getShopInfoId());
                map.put(Parameterkey.useTime, appointDate_upLoad);//选中的时间
                map.put(Parameterkey.siteList, siteList_upLoad);//房间和房间内的时间段选择器

//                LogUtils.json(ConstantSign.LOGCAT_NOMAL + "->真实上传的 siteList_upLoad=", siteList_upLoad);

                AddLogUpLoadInfo addLogUpLoadInfo = new AddLogUpLoadInfo();
                addLogUpLoadInfo.setActivity(mActivityInstance);
                addLogUpLoadInfo.setWhat(ConstantApi.WHAT_GETRESERVATIONFORSITEANDPAY_URL);//请求数字标识
                addLogUpLoadInfo.setUrlPath(ApiService.getReservationForSiteAndPay_url);//url地址
                addLogUpLoadInfo.setRequestMethod(ConstantSign.REQUEST_METHOD_POST);//POST 或者 GET
                addLogUpLoadInfo.setToastToUser(true);//展示给用户的标志
                addLogUpLoadInfo.setHashMapParameter(map);

                //做上传的json
                String jsonUpLoad = JSON.toJSONString(map, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue);
//                String jsonUpLoad = JSON.toJSONString(map);

                NetworkManager.getInstance().initRetrofitRxJava()
                        .create(ApiService.class)
                        .getReservationForSiteAndPay(RequestBody.create(jsonUpLoad,
                                MediaType.parse(ApiService.HEADER_JSON)))
                        .compose(PaintBookingMainActivity.this.bindUntilEvent(ActivityEvent.DESTROY))//
                        .compose(new ResponseTransformer<>(addLogUpLoadInfo, new ApiRequestSubListener<PaintBookingPayFee>() {
                            @Override
                            public void handlerSomeThingNotSuccessDataForItSelf(int what_method, String serverCode, String serverMessage) {
                                super.handlerSomeThingNotSuccessDataForItSelf(what_method, serverCode, serverMessage);

                                CommUtils.checkMaterialDialog(materialDialog);

                                //如果有报错要特别提示

                            }
                        })).doOnSubscribe(new Consumer<Disposable>() {
                            @Override
                            public void accept(Disposable disposable) throws Throwable {

//                                CommUtils.checkMaterialDialog(materialDialog);
                                //进度圈圈
                                method_create_materialDialog(mActivityInstance, ConstantSign.TIPS_SUBMIT);

                            }
                        }).subscribe(new Consumer<PaintBookingPayFee>() {
                            @Override
                            public void accept(PaintBookingPayFee paintBookingPayFeeValue) throws Throwable {

                                CommUtils.checkMaterialDialog(materialDialog);

                                if (paintBookingPayFeeValue != null) {

                                    // : 2023-10-27 14:56 人为测试 isPay 是false，不让到结算页，并且设置人为勾灭的值，测试代码勿删除；
                                    //----------------------------------------------------------
//                                    paintBookingPayFeeValue.setPay(false);
//                                    paintBookingPayFeeValue.getUnSelectedSpanIds().add("1314");
//                                    paintBookingPayFeeValue.getUnSelectedSpanIds().add("1316");
                                    //----------------------------------------------------------

                                    //判断值是否为真
                                    boolean isPay = paintBookingPayFeeValue.isPay();

                                    if (isPay) {

//                                      LogUtils.json(ConstantSign.LOGCAT_NOMAL + "paintBookingPayFeeValue=", paintBookingPayFeeValue);

                                        Bundle extra_bundle = new Bundle();
                                        //将这段json携带过去，为的是刷新下个页面，
                                        extra_bundle.putString(ExtraKey.EXTRA_PAINT_BOOKING_PAYFEE_PARAMETER, jsonUpLoad);

                                        extra_bundle.putParcelable(ExtraKey.EXTRA_PAINTBOOKINGPAYFEE, paintBookingPayFeeValue);

                                        ActivityUtils.startActivity(extra_bundle, PaintBookingFeeActivity.class);

                                    } else {

                                        //添加
                                        ToastUtils.showShort(getResources().getString(R.string.paintbookingabnomal));

                                        //还原 不可用的id;
                                        ArrayList<String> listIds = (ArrayList<String>) paintBookingPayFeeValue.getUnSelectedSpanIds();

                                        //双重遍历所有房间，给id的状态还原
                                        if (listIds != null && !listIds.isEmpty()) {

                                            //--------------------------------------------------------------------------------------------------------------

                                            for (String itemId : listIds) {

                                                //for遍历
                                                if (mDataResources != null && !mDataResources.isEmpty()) {

                                                    for (BookingOutsideBean itemOutSide : mDataResources) {

                                                        if (itemOutSide != null) {

                                                            for (BookingInsideBean itemInSide : itemOutSide.getSiteTimeSpans()) {

                                                                if (itemInSide != null) {

                                                                    //找到对应的id
                                                                    String siteTimeSpanId_current = String.valueOf(itemInSide.getSiteTimeSpanId());
                                                                    //是否可用的
                                                                    boolean useable = itemInSide.isUsable();

                                                                    if (useable) {

                                                                        if (TextUtils.equals(siteTimeSpanId_current, itemId)) {

                                                                            if (itemInSide.isChecked()) {

                                                                                itemInSide.setChecked(false);
                                                                                itemInSide.setUsable(false);

                                                                                LogUtils.json(ConstantSign.LOGCAT_NOMAL + "被迫调整的预约时段-有效数据是-----itemInSide--", itemInSide);

                                                                            }

                                                                        }

                                                                    }


                                                                }

                                                            }
                                                        }

                                                    }

                                                }

                                            }

                                            //--------------------------------------------------------------------------------------------------------------

                                            //值改变之后重新刷新适配器；？或者直接重新刷新这接口？
                                            //2023年10月27日14:48:10 议论是：如果
                                            if (bookingOutsideAdapter != null) {
                                                bookingOutsideAdapter.notifyDataSetChanged();
                                            }


                                        }
                                    }
                                }
                            }
                        }, new ErrorConsumer() {
                            @Override
                            protected void error(ApiException apiException) {

                                //页面报错；
                                CommUtils.checkMaterialDialog(materialDialog);

                            }
                        });

                break;

            }

            default:
                break;
        }

    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {

        //先加载
//        viewBindingParent = ActivityPaintBookingMainBinding.inflate(getLayoutInflater());
//        activityPaintBookingMainBinding = ActivityPaintBookingMainBinding.inflate(getLayoutInflater());
//        setContentView(activityPaintBookingMainBinding.getRoot());

        super.onCreate(savedInstanceState);

//        mWinXinApi = WXAPIFactory.createWXAPI(this, PushConstants.WEIXIN_APPID);//红色物业的微信id
//
//        if (mWinXinApi != null) {
//            mWinXinApi.registerApp(PushConstants.WEIXIN_APPID);
//            LogUtils.d("itchen--微信--registerApp");
//        }

//        if (activityPaintBookingMainBinding != null) {
//            if (activityPaintBookingMainBinding.getRoot() != null) {
//                LogUtils.d(ConstantSign.LOGCAT_NOMAL+"activityPaintBookingMainBinding.getRoot()-->"+activityPaintBookingMainBinding.getRoot());
//                setContentView(activityPaintBookingMainBinding.getRoot());
//                super.onCreate(savedInstanceState);
//            }
//        } else {
//        }
//        activityPaintBookingMainBinding = (ActivityPaintBookingMainBinding) viewBindingParent;

        processExtraData();

        initloading();

        initViews();

        gainDatas();

        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }

    }

    @Override
    protected int getContentViewId() {
        return R.layout.activity_paint_booking_main;
    }

    @Override
    protected void initImmersionBar() {
        super.initImmersionBar();

        ImmersionBar.with(this)//
                .titleBar(R.id.toolbarygxskout)
                .fitsSystemWindows(true)//解决状态栏和布局重叠问题，任选其一，默认为false，当为true时一定要指定statusBarColor()，不然状态栏为透明色，还有一些重载方法
                //.statusBarColor(R.color.colorPrimary)//
                //.navigationBarColor(R.color.colorPrimary)//
                //.keyboardEnable(true)
                .init();

    }

    @Override
    protected void initToolBar(ToolbarHelper toolbarHelper) {

        toolbarHelper.setTitle(getString(R.string.paint_booking_create));
        toolbarHelper.setVersionName(true, AppUtils.getAppVersionName());
        toolbarHelper.setLayoutClose(false, "", null);
        toolbarHelper.setLayoutLeft(true, R.drawable.backicon, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //搜索客户信息，优先关闭软键盘
                KeyboardUtils.hideSoftInput(mActivityInstance);
                methodBack();
            }
        });

        //核销的历史记录顶部啥都没有；
//        toolbarHelper.setLayoutRight(false, 0, "", null);
        //添加潜在客户的按钮
        toolbarHelper.setLayoutRight(true, 1, getString(R.string.paint_booking_history), new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                //2023-07-25 21:39 携带二维码的信息;
                Bundle bundle = new Bundle();
//                bundle.putInt(ExtraKey.EXTRA_QRCODE_INFO, 0);
//                bundle.putInt(ExtraKey.BGAQRCODE_KEY, ExtraValue.BGAQRCODE_VALUE_FROM_CARD_DIST_HISTORY);
                ActivityUtils.startActivity(bundle, PaintBookingSumHistoryActivity.class);

//                LogUtils.d(ConstantSign.LOGCAT_NOMAL + "测试代码测试点击");
            }
        });

    }

    @Override
    protected void onClickNodata(View v) {
        gainDatas();
    }

    @Override
    protected void initViews() {

//        ArrayList<BookingInsideBean> listInSide = new ArrayList<>();
//
//        BookingInsideBean bookingInsideBean0 = new BookingInsideBean();
//        bookingInsideBean0.setTimePeriodId("111");
//        bookingInsideBean0.setTimePeriodValue("08:00");
//        listInSide.add(bookingInsideBean0);
//
//        BookingInsideBean bookingInsideBean1 = new BookingInsideBean();
//        bookingInsideBean1.setTimePeriodId("222");
//        bookingInsideBean1.setTimePeriodValue("09:00");
//        listInSide.add(bookingInsideBean1);
//
//        BookingInsideBean bookingInsideBean2 = new BookingInsideBean();
//        bookingInsideBean2.setTimePeriodId("333");
//        bookingInsideBean2.setTimePeriodValue("10:00");
//        listInSide.add(bookingInsideBean2);
//
//        BookingInsideBean bookingInsideBean3 = new BookingInsideBean();
//        bookingInsideBean3.setTimePeriodId("444");
//        bookingInsideBean3.setTimePeriodValue("11:00");
//        listInSide.add(bookingInsideBean3);
//
//        BookingInsideBean bookingInsideBean4 = new BookingInsideBean();
//        bookingInsideBean4.setTimePeriodId("555");
//        bookingInsideBean4.setTimePeriodValue("12:00");
//        listInSide.add(bookingInsideBean4);
//
//        BookingInsideBean bookingInsideBean5 = new BookingInsideBean();
//        bookingInsideBean5.setTimePeriodId("666");
//        bookingInsideBean5.setTimePeriodValue("13:00");
//        listInSide.add(bookingInsideBean5);
//
//        BookingOutsideBean bookingOutsideBean = new BookingOutsideBean();
//        bookingOutsideBean.setBookingOutsideId("11");
//        bookingOutsideBean.setRoomName("蓝色喷涂");
//        bookingOutsideBean.setDataList(listInSide);
//        mDataResources.add(bookingOutsideBean);
//
//        //-------------------------------------------------------------------------------
//
//        ArrayList<BookingInsideBean> listInSide1 = new ArrayList<>();
//
//        BookingInsideBean bookingInsideBean00 = new BookingInsideBean();
//        bookingInsideBean00.setTimePeriodId("111");
//        bookingInsideBean00.setTimePeriodValue("08:00");
//        listInSide1.add(bookingInsideBean00);
//
//        BookingInsideBean bookingInsideBean11 = new BookingInsideBean();
//        bookingInsideBean11.setTimePeriodId("222");
//        bookingInsideBean11.setTimePeriodValue("09:00");
//        listInSide1.add(bookingInsideBean11);
//
//        BookingInsideBean bookingInsideBean22 = new BookingInsideBean();
//        bookingInsideBean22.setTimePeriodId("333");
//        bookingInsideBean22.setTimePeriodValue("10:00");
//        listInSide1.add(bookingInsideBean22);
//
//        BookingInsideBean bookingInsideBean33 = new BookingInsideBean();
//        bookingInsideBean33.setTimePeriodId("444");
//        bookingInsideBean33.setTimePeriodValue("11:00");
//        listInSide1.add(bookingInsideBean33);
//
//        BookingInsideBean bookingInsideBean44 = new BookingInsideBean();
//        bookingInsideBean44.setTimePeriodId("444");
//        bookingInsideBean44.setTimePeriodValue("12:00");
//        listInSide1.add(bookingInsideBean44);
//
//
//        BookingOutsideBean bookingOutsideBean1 = new BookingOutsideBean();
//        bookingOutsideBean1.setBookingOutsideId("11");
//        bookingOutsideBean1.setRoomName("红色喷涂");
//        bookingOutsideBean1.setDataList(listInSide1);
//        mDataResources.add(bookingOutsideBean1);

//        -------------------------------------------------------------------------------
        //先计算当前时间
        appointDate_current = TimeUtils.date2String(TimeUtils.getNowDate(), TimeUtilSer.simplemore);
        //默认是当前时间
        appointDate_upLoad = appointDate_current;

        //这样变成具体的
        if (recyclerViewInBooking != null) {

//            LogUtils.d(ConstantSign.LOGCAT_NOMAL + "recyclerViewInBooking--不是空的");
            recyclerViewInBooking.setLayoutManager(new MyLinearLayoutManager(this));

            //适配器填充
//           activityPaintBookingMainBinding.recyclerViewInBooking.setAdapter();

            bookingOutsideAdapter = new BookingOutsideAdapter(R.layout.bookingoutsideadapter, mDataResources, ExtraValue.COME_FROM_PAINT_BOOKING_MAIN_ACTIVITY);
            bookingOutsideAdapter.removeAllHeaderView();

            bookingOutsideAdapter.addHeaderView(getHeaderView(recyclerViewInBooking));
            recyclerViewInBooking.setAdapter(bookingOutsideAdapter);
            bookingOutsideAdapter.notifyDataSetChanged();

        }


        if (refreshLayoutInBooking != null) {

//            LogUtils.d(ConstantSign.LOGCAT_NOMAL + "refreshLayoutInBooking--不是空的");

            refreshLayoutInBooking.setEnableRefresh(true);
            refreshLayoutInBooking.setOnRefreshListener(new OnRefreshListener() {
                @Override
                public void onRefresh(@NonNull RefreshLayout refreshLayout) {

//                    LogUtils.d(ConstantSign.LOGCAT_NOMAL + "refreshLayoutInBooking--下拉刷新执行--外侧的");

                    //仅仅只有下拉刷新的内容
                    refreshLayout.getLayout().post(new Runnable() {
                        @Override
                        public void run() {

//                          LogUtils.d(ConstantSign.LOGCAT_NOMAL + "refreshLayoutInBooking--下拉刷新执行");

                            gainDatas();

                            refreshLayout.finishRefresh();

                        }
                    });

                }
            });
        } else {
            LogUtils.d(ConstantSign.LOGCAT_NOMAL + "是空的？");
        }

//         测试崩溃采集日志
//        int index = 0;
//        int result = 11 / 0;

    }

    private View getHeaderView(RecyclerView _recyclerViewWork) {

        View workHeader;
        if ((_recyclerViewWork != null) && (_recyclerViewWork.getParent() != null)) {
            workHeader = LayoutInflater.from(PaintBookingMainActivity.this).inflate(//
                    R.layout.header_select_time, //
                    (ViewGroup) _recyclerViewWork.getParent(),//
                    false);//
        } else {
            workHeader = LayoutInflater.from(PaintBookingMainActivity.this).inflate(R.layout.header_select_time, null);
        }

        //外侧的填充
        RelativeLayout linearLayoutChooseMiddletallTime = (RelativeLayout) workHeader.findViewById(R.id.linearlayoutchoosemiddletalltime);
        //日期填充
        TextView textViewStartTimeInWorkBook = (TextView) workHeader.findViewById(R.id.textviewstarttimeinworkbook);
        //默认日期填充是当天的日期
        if (textViewStartTimeInWorkBook != null) {
            textViewStartTimeInWorkBook.setText(appointDate_upLoad);
        }

        linearLayoutChooseMiddletallTime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                //时间弹窗
                // TODO: 2023-09-21 15:26 时间弹窗
                KeyboardUtils.hideSoftInput(mActivityInstance);

                CalendarViewCustomPopup calendarViewCustomPopup = new CalendarViewCustomPopup(ExtraValue.MODIFY_PAINT_BOOKING_TIME_SELECT,
                        1,
                        PaintBookingMainActivity.this, false);

                basePopupViewAgreenmentTime = new XPopup.Builder(PaintBookingMainActivity.this)
                        .hasShadowBg(true)
                        .moveUpToKeyboard(false) //如果不加这个，评论弹窗会移动到软键盘上面
                        .isViewMode(true)
                        .isDestroyOnDismiss(true) //对于只使用一次的弹窗，推荐设置这个
                        .isThreeDrag(false) //是否开启三阶拖拽，如果设置enableDrag(false)则无效
                        .asCustom(calendarViewCustomPopup)
                        .show();


            }
        });

        //监听选中的签约时间
        mCompositeDisposable.add(RxBus.getInstance()
                .toObserverable(RxBusCalendarTimeForAgreement.class)//
                .subscribeOn(AndroidSchedulers.mainThread())//
                .observeOn(AndroidSchedulers.mainThread())//
                .subscribe(new Consumer<RxBusCalendarTimeForAgreement>() {

                    @Override
                    public void accept(RxBusCalendarTimeForAgreement rxBusCalendarTimeForAgreement) throws Throwable {

                        if (rxBusCalendarTimeForAgreement != null) {

                            if (rxBusCalendarTimeForAgreement.getActionFlag() == ExtraValue.MODIFY_PAINT_BOOKING_TIME_SELECT) {

                                //【筛选是签约时间】；
                                appointDate_upLoad = rxBusCalendarTimeForAgreement.getManufactureDate();
                                LogUtils.d(ConstantSign.LOGCAT_NOMAL + "选中的 预约时间 agreeMentTimeSelect-->" + appointDate_upLoad);

                                //判断空值
                                if (TextUtils.isEmpty(appointDate_upLoad)) {
                                    //选择时间异常，请重新选择；
                                    CommUtils.checkDialog(mAlertView);
                                    mAlertView = CommUtils.method_showAlertViewSingleSlowly(mActivityInstance, ConstantSign.ALERT_TITLE, getString(R.string.middletallstarttimeabnomalnull), true);
                                    mAlertView.show();
                                    return;
                                }

                                //【开始时间】不能比【完成期限】更靠后:即是：如果【开始时间-大于完成时间，】那么弹窗提示，返回执行；
                                boolean compareTime = DateUtilFir.comparTwoTime(appointDate_current, appointDate_upLoad);
                                if (compareTime) {
                                    CommUtils.checkDialog(mAlertView);
                                    mAlertView = CommUtils.method_showAlertViewSingleSlowly(mActivityInstance, ConstantSign.ALERT_TITLE, getString(R.string.middletallstarttimeaftercompletetime), true);
                                    mAlertView.show();
                                    return;
                                }

                                //判断适配器，从适配器之中取值textView赋值
                                if (textViewStartTimeInWorkBook != null) {
                                    textViewStartTimeInWorkBook.setText(rxBusCalendarTimeForAgreement.getManufactureDate());
                                }

                                //需要刷新接口数据
                                gainDatas();

                            }
                        }
                    }
                }));

        return workHeader;

    }

    @Override
    protected void gainDatas() {

        //清空原始数据
        if (mDataResources != null && !mDataResources.isEmpty()) {
            mDataResources.clear();
        }

        if (bookingOutsideAdapter != null) {
            bookingOutsideAdapter.notifyDataSetChanged();
        }

        if (NetworkUtils.isConnected()) {

            getServerDatas();

        } else {
            netWorkError();
        }

    }

    //获取喷涂房间和可以预约的时间段；
    private void getServerDatas() {

        HashMap<String, Object> map = new HashMap<>();
        map.put(Parameterkey.shopInfoId, mSession.getShopInfoId());
        map.put(Parameterkey.appointDate, appointDate_upLoad);
//        map.put(Parameterkey.appointDate, TimeUtils.date2String(TimeUtils.getNowDate(), TimeUtilSer.simplemore));

        AddLogUpLoadInfo addLogUpLoadInfo = new AddLogUpLoadInfo();
        addLogUpLoadInfo.setActivity(mActivityInstance);
        addLogUpLoadInfo.setWhat(ConstantApi.WHAT_GETUNUSEDSITELIST_URL);//请求数字标识
        addLogUpLoadInfo.setUrlPath(ApiService.getUnusedSiteList_url);//url地址
        addLogUpLoadInfo.setRequestMethod(ConstantSign.REQUEST_METHOD_POST);//POST 或者 GET
        addLogUpLoadInfo.setToastToUser(true);//展示给用户的标志
        addLogUpLoadInfo.setHashMapParameter(map);

        NetworkManager.getInstance().initRetrofitRxJava()
                .create(ApiService.class)
                .getUnusedSiteList(RequestBody.create(JSON.toJSONString(map, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue),
                        MediaType.parse(ApiService.HEADER_JSON)))
                .compose(PaintBookingMainActivity.this.bindUntilEvent(ActivityEvent.DESTROY))//
                .compose(new ResponseTransformer<>(addLogUpLoadInfo, new ApiRequestSubListener<ArrayList<BookingOutsideBean>>() {
                    @Override
                    public void handlerSomeThingNotSuccessDataForItSelf(int what_method, String serverCode, String serverMessage) {
                        super.handlerSomeThingNotSuccessDataForItSelf(what_method, serverCode, serverMessage);
                        methodNotSuccessData(what_method, serverCode, serverMessage);
                    }
                })).doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Throwable {

                        loadingGone();

                    }
                }).subscribe(new Consumer<ArrayList<BookingOutsideBean>>() {
                    @Override
                    public void accept(ArrayList<BookingOutsideBean> bookingOutsideBeanArrayList) throws Throwable {

                        //清空原始数据
                        if (mDataResources != null && !mDataResources.isEmpty()) {
                            mDataResources.clear();
                        }

                        if (bookingOutsideBeanArrayList != null && !bookingOutsideBeanArrayList.isEmpty()) {
                            if (mDataResources != null) {
                                mDataResources.addAll(bookingOutsideBeanArrayList);
                            }
                        }

                        //这里也不用管是下拉刷新或者上拉加载更多，直接判断是否为空，
                        if (mDataResources != null && mDataResources.isEmpty()) {
                            //同时禁用加载更多；
                            fillNullDataView(StringUtils.getString(R.string.nulldatanow), R.drawable.errorsear);
                        }

                        if (bookingOutsideAdapter != null) {
                            bookingOutsideAdapter.notifyDataSetChanged();
                        }

                    }
                }, new ErrorConsumer() {

                    @Override
                    protected void error(ApiException apiException) {

                        //页面报错；

                    }
                });

    }

    @Override
    public void methodNotSuccessData(int what_method, String serverCode, String serverMessage) {
        super.methodNotSuccessData(what_method, serverCode, serverMessage);

        switch (what_method) {

            case ConstantApi.GETSHOPLATENTCUSTOMERLIST_URL: {

                if (mDataResources != null && mDataResources.isEmpty()) {

                    CommUtils.checkCurrently((ErrorActivity) mActivityInstance,//
                            serverCode,//
                            R.drawable.errorsear,//
                            serverMessage,//
                            getString(R.string.nulldatanow));
                }

                break;
            }

            default:
                break;
        }
    }

//    private void showPayDialog() {
//
//        /*if(dialogFragment!=null &&  dialogFragment.getDialog()!=null
//                && dialogFragment.getDialog().isShowing()) {
//            //dialog is showing so do something
//        } else {
//            //dialog is not showing
//        }*/
//
//        closePayDialg(payDialogPanel);
//
//        payDialogPanel = BottomDialog.create(getSupportFragmentManager())//
//
//                .setViewListener(new BottomDialog.ViewListener() {//
//                    @Override
//                    public void bindView(View view) {//
//
//                        //携带三个参数去创建支付面板。
//                        initPayView(view, payTypeLists, payTypeCode);
//
//                    }
//                }).setLayoutRes(R.layout.paydialog_layout)//
//                .setDimAmount(0.5f)//
//                .setCancelOutside(false)//支付宝的弹窗之外不可再次点击消失
//                .setTag("paymentfee")//
//                .show();//
//
//    }


//    private void initPayView(View _view,//
//                             ArrayList<PayTypeList> _payTypeListFromServer,//
//                             String _payTypeFromServer) {//
//
//        //点击按钮功能
//        RelativeLayout layoutClosePay = (RelativeLayout) _view.findViewById(R.id.layoutclosepay);
//        com.flyco.roundview.RoundTextView textviewpayliji = (RoundTextView) _view.findViewById(R.id.textviewpayliji);
//
//        //直接给监听器传递到适配器中?
//        //列表支付
//        PayTypeAdapter payTypeAdapter = new PayTypeAdapter(//
//                PaintBookingMainActivity.this, //
//                PaintBookingMainActivity.this, //
//                _payTypeListFromServer,//支付返回的支付列表内容
//                _payTypeFromServer);//传入服务器返回来的支付的方式进来
//
//        if (payTypeAdapter != null) {
//
//            payTypeAdapter.setPayTypeListener(new PayTypeAdapter.PayTypeListener() {
//
//                @Override
//                public void payType(PayTypeList payTypeList) {
//
//                    //传回支付方式
//                    curCheckPayTypeBean = payTypeList;
//                }
//
//                @Override
//                public void setPayTypeList(PayTypeList payTypeList) {
//                    //传回来支付方式-这个暂时只是用来，在默认支付方式的时候用到
//                    curCheckPayTypeBean = payTypeList;
//                }
//            });
//
//        }
//
//        ListView listViewPayList = (ListView) _view.findViewById(R.id.listViewPayList);
//        listViewPayList.setAdapter(payTypeAdapter);//
//
//        if (payTypeAdapter != null) {
//            payTypeAdapter.notifyDataSetChanged();
//        }
//
//        //立即付款内容。
//        textviewpayliji.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//
////                checkPayWay();//立即付款
//
//                //methodOrderState();//测试
//            }
//        });
//
//        //叉号按钮点击关闭面板。
//        layoutClosePay.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//
//                //清空下勾选支付方式。
//
//
//                //关闭弹窗面板内容。
//                /*if (payDialogPanel != null) {
//                    payDialogPanel.dismiss();
//                }*/
//
//                closePayDialg(payDialogPanel);
//
//            }
//        });
//
//    }

//    private void closePayDialg(BaseBottomDialog _payDialogPanel) {
//
//        if (_payDialogPanel != null) {
//            if (_payDialogPanel.getDialog() != null && _payDialogPanel.getDialog().isShowing()) {
//                //_payDialogPanel.dismiss();
//                //2019年09月19日改造
//                _payDialogPanel.dismissBottomDialog();
//                //payDialogPanel.dismissAllowingStateLoss();
//            }
//        }
//    }

    /**
     * 过滤是选择了哪个支付方式
     */
//    private void checkPayWay() {
//
//        //检查是微信支付还是支付宝支付等方式内容
//        //不能用弹窗,用弹窗就展示在支付面板背后去了。
//        if (curCheckPayTypeBean == null) {
////          CommUtils.displayToastShort(PaymentFeeActivity.this, "请选择支付方式");
//            return;
//        }
//
//        //检测支付方式
//        if (curCheckPayTypeBean != null) {
//
//            //如果选择的是微信支付
//            if (TextUtils.equals(curCheckPayTypeBean.getPayTypeCode(), ConstantSign.PAY_WECHAT)) {
//
//                if (mWinXinApi != null) {
//
//                    if (!mWinXinApi.isWXAppInstalled()) {
//
//                        CommUtils.checkDialog(mAlertView);
//                        mAlertView = CommUtils.method_showAlertViewSingleSlowly(mActivityInstance, ConstantSign.ALERT_TITLE, getString(R.string.not_install_wechat), true);
//                        mAlertView.show();
//
//                        return;
//                    }
//
//                }
//            }
//
//        }
//
//        //已经点选了支付方式，那么走正常逻辑
//        //2018年04月16日逻辑大管家支付这里有个问题，需要先判断钱包够不够，输入密码之后，再调用paytoken
//        if (TextUtils.equals(curCheckPayTypeBean.getPayTypeCode(), ConstantSign.PAY_DGJ)) {//如果支付方式选择的是：大管家支付
//
//            passwordStringPass = "";//重置下
//            //关闭支付列表面板
//            closePayDialg(payDialogPanel);
//            //弹出底部的面板内容：先判断钱包等够不够，
//            method_checkWallet(beforeReceiptNo);
//
//        } else {//在线的。非大管家支付一开始的通用逻辑
//
//            passwordStringPass = "";//重置下
//            //关闭支付列表面板
//            closePayDialg(payDialogPanel);
//
////            getPayToken(beforeReceiptNo);
//
//        }
//
//        //2018年04月17日添加大管家支付逻辑，这个单独通用逻辑不要-将来可能有其他需要放开。
//        //getPayToken(beforeReceiptNo);
//
//    }

    /**
     * 勾选了大管家卡支付那么检查钱包够不够。
     */
//    private void method_checkWallet(final String _beforeOrderNo) {

//        if (NetworkUtils.isConnected()) {
    //根据订单编号查询余额是否充足弹窗提示、测试
    //String requestUrl = Constants.getInstance().walletCheck();

//            CommUtils.checkMaterialDialog(materialDialogSendPayWallet);
//            materialDialogSendPayWallet = CommUtils.createMaterialDialog(mActivityInstance, "请求中");
//
//            Request<JSONObject> request = NoHttp.createJsonObjectRequest(Constants.getInstance().walletCheck(), RequestMethod.POST);
//            Map<String, Object> jsonObjectCheck = new HashMap<String, Object>();
//            jsonObjectCheck.put("beforeOrderNo", _beforeOrderNo);//已经生成的订单编号
//
//            request.setDefineRequestBodyForJson(JSON.toJSONString(jsonObjectCheck));
//
//            startRequest(ConstantApi.WHAT_PAYWALLET_BALANCE, request, jsonObjectCheck, httpListener, true, true);
//        } else {
//            CommUtils.displayToastShort(PaymentFeeActivity.this, ConstantApi.NONET);
//        }
//    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThreadInPaintBookingMain(EventPaintBookingMain eventPaintBookingMain) {

        if (eventPaintBookingMain != null) {

            if (eventPaintBookingMain.getMessage() == ExtraValue.EVENTBUS_EVENT_TO_REFRESH_PAINTBOOKING_MAIN_PAGE) {

                //如果发起搜索，要重置 第1页
//                pagination_upLoad = Parameterkey.pageNum_default_first;

                //所有现有记录均清空，包括选中状态
                if (mDataResources != null && !mDataResources.isEmpty()) {
                    mDataResources.clear();
                }

                if (bookingOutsideAdapter != null) {
                    bookingOutsideAdapter.notifyDataSetChanged();
                }

                getServerDatas();

            }
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();

        //该页面没有微信支付等；
//        if (mWinXinApi != null) {
//            mWinXinApi.
//        }

        if (basePopupViewAgreenmentTime != null) {
            basePopupViewAgreenmentTime.onDestroy();
            basePopupViewAgreenmentTime = null;
        }

        if (mDataResources != null && !mDataResources.isEmpty()) {
            mDataResources.clear();
//            mDataResources = null;
        }

        if (bookingOutsideAdapter != null) {
            bookingOutsideAdapter.notifyDataSetChanged();
            bookingOutsideAdapter = null;
        }

        if (mDataResources != null) {
            mDataResources = null;
        }

        if (siteList_upLoad != null && !siteList_upLoad.isEmpty()) {
            siteList_upLoad.clear();
            siteList_upLoad = null;
        }


        EventBus.getDefault().unregister(this);

    }


    @Override
    protected void methodBack() {
        methodBackFinish();
    }

    @Override
    public void processExtraData() {

        //use the data received here
        Bundle bundle = this.getIntent().getExtras();

        if (bundle != null) {

            flag_jumpfrom_where = bundle.getInt(ExtraKey.EXTRA_JUMPFROM_WHERE);
            //LogUtils.d(ConstantSign.LOGCAT_NOMAL + extra_jumpfrom_where);
//            station_shopId_upLoad = bundle.getString(ExtraKey.EXTRA_ASSETINSIDEBEAN_SHOPID);
            //这个特殊，采用同一个对象；
            //服务站的顶部选择列表---这里取到的肯定是空值，因为上一个页面没有携带
//            extra_assetStationInfoListForAddAsset_loacalDB = bundle.getParcelableArrayList(ExtraKey.EXTRA_ASSETSTATIONINFOLISTFORADDASSET);

            //资产的归属方 列表，
//            extra_assetUnderBusinessInfoListOutSide = bundle.getParcelableArrayList(ExtraKey.EXTRA_ASSETUNDERBUSINESSINFOLISTOUTSIDE);
        }
    }
}